package example.springboot.controller;

import example.springboot.common.Result;
import example.springboot.dto.LoginRequest;
import example.springboot.dto.LoginResponse;
import example.springboot.service.UserService;
import example.springboot.util.SystemLogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 *
 * @Author 董熠涛
 * @Date 2025/6/16 20:22
 */
@RestController
@RequestMapping("/api/auth")
@CrossOrigin
public class AuthController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@RequestBody LoginRequest loginRequest) {
        try {
            // 验证参数
            if (loginRequest.getUsername() == null || loginRequest.getUsername().trim().isEmpty()) {
                return Result.error("用户名不能为空");
            }
            if (loginRequest.getPassword() == null || loginRequest.getPassword().trim().isEmpty()) {
                return Result.error("密码不能为空");
            }

            // 执行登录（管理后台要求管理员角色）
            LoginResponse loginResponse = userService.login(loginRequest, true);
            // 记录登录日志
            SystemLogUtil.logLogin(loginRequest.getUsername(), true);
            return Result.success("登录成功", loginResponse);
        } catch (RuntimeException e) {
            // 记录登录失败日志
            SystemLogUtil.logLogin(loginRequest.getUsername(), false);
            return Result.error(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            // 记录登录失败日志
            SystemLogUtil.logLogin(loginRequest.getUsername(), false);
            return Result.error("登录失败：" + e.getMessage());
        }
    }

    /**
     * 测试接口 - 验证服务是否正常运行
     */
    @GetMapping("/test")
    public Result<String> test() {
        return Result.success("API服务运行正常");
    }
}

